<template>
  <Dialog :title="'佣金设置'" v-model="dialogVisible" width="1200px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="commission-setting-form"
      size="large"
      v-loading="formLoading"
    >
     
      <el-form-item label="佣金设置" prop="commissionSettings">
        <div v-for="(item, index) in formData.commissionSettings" :key="index" class="commission-setting-row">
          <el-radio-group v-model="item.targetType" @change="() => handleTargetTypeChange(item, index)" style="margin-right: 12px;">
            <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_TARGET_TYPE)" :key="dict.value" :label="dict.value">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
          <el-select
            v-model="item.targetId"
            filterable
            remote
            clearable
            :remote-method="(query) => remoteSearchTarget(item, index, query)"
            :loading="item.targetLoading"
            :placeholder="getTargetPlaceholder(item.targetType)"
            style="width: 200px; margin-right: 12px;"
            @focus="() => remoteSearchTarget(item, index, '')"
          >
            <el-option
              v-for="option in item.targetOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <el-radio-group v-model="item.commissionType" style="margin-right: 12px;">
            <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_COMMISSION_RATE)" :key="dict.value" :label="dict.value">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
          <el-input
            v-if="item.commissionType === 1"
            v-model="item.commissionRate"
            placeholder="请输入佣金比例"
            style="width: 120px; margin-right: 12px;"
          />
          <el-input
            v-if="item.commissionType === 2"
            v-model="item.fixedAmount"
            placeholder="请输入固定佣金金额"
            style="width: 120px; margin-right: 12px;"
          />
          <el-button type="danger" link @click="removeCommissionSetting(index)" v-if="formData.commissionSettings.length > 1">删除</el-button>
        </div>
        <el-button type="primary" link @click="addCommissionSetting" style="margin-top: 8px;">
          <Icon icon="ep:plus" class="mr-5px" /> 添加佣金设置
        </el-button>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">保存</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { ChannelCommissionSettingVO,ChannelCommissionSettingApi } from '@/api/mall/product/channelcommissionsetting'
import { TradeChannelAgreementApi } from '@/api/member/channelagreement'
import { CategoryLevelApi } from '@/api/mall/product/categorylevel'
import { getCategoryList } from '@/api/mall/product/category'
import { getSpuPage } from '@/api/mall/product/spu'
import request from '@/config/axios'

const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)

interface CommissionSettingItem {
  targetType: number | undefined;
  targetId: number | undefined;
  commissionType: number | undefined;
  commissionRate: number | undefined;
  fixedAmount: number | undefined;
  targetOptions: { label: string; value: any }[];
  targetLoading: boolean;
}

const formData = reactive<{
  agreementId: number | undefined;
  commissionSettings: CommissionSettingItem[];
  status: number | undefined;
  remark: string;
}>({
  agreementId: undefined,
  commissionSettings: [] as CommissionSettingItem[],
  status: undefined,
  remark: ''
})

const formRules = {
  agreementId: [{ required: true, message: '合作协议不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
}

function createEmptySetting() {
  return {
    targetType: undefined,
    targetId: undefined,
    commissionType: undefined,
    commissionRate: undefined,
    fixedAmount: undefined,
    targetOptions: [],
    targetLoading: false
  }
}

function addCommissionSetting() {
  formData.commissionSettings.push(createEmptySetting())
}
function removeCommissionSetting(index) {
  formData.commissionSettings.splice(index, 1)
}
function handleTargetTypeChange(item, index) {
  item.targetId = undefined
  item.targetOptions = []
}
async function remoteSearchTarget(item, index, query) {
  item.targetLoading = true
  let options = []
  try {
    if (item.targetType === 1) {
      const res = await CategoryLevelApi.getCategoryLevelPage({ name: query, pageNo: 1, pageSize: 20 } as any)
      options = (res.list || []).map(i => ({ label: i.name, value: i.id }))
    } else if (item.targetType === 2) {
      const res = await getCategoryList({ name: query } as any)
      options = (res || []).map(i => ({ label: i.name, value: i.id }))
    } else if (item.targetType === 3) {
      const res = await getSpuPage({ name: query, pageNo: 1, pageSize: 20 } as any)
      options = (res.list || []).map(i => ({ label: i.name, value: i.id }))
    }
  } finally {
    item.targetOptions = options
    item.targetLoading = false
  }
}

function getTargetPlaceholder(type: number | undefined) {
  if (type === 1) return '请选择分类级别'
  if (type === 2) return '请选择分类'
  if (type === 3) return '请选择商品'
  return '请选择目标'
}

function getTargetError(type: number | undefined) {
  if (type === 1) return '分类级别为必填项'
  if (type === 2) return '分类为必填项'
  if (type === 3) return '商品为必填项'
  return '目标为必填项'
}

async function open(agreementId) {
  dialogVisible.value = true
  // 获取协议详情
  const agreement = await TradeChannelAgreementApi.getTradeChannelAgreementById(agreementId)
  formData.agreementId = agreementId
  formData.status = agreement.status
  formData.remark = agreement.remark
  if (agreement.commissionSettings && Array.isArray(agreement.commissionSettings)) {
    // 编辑时，targetId 显示名称
    formData.commissionSettings = await Promise.all(agreement.commissionSettings.map(async (item) => {
      let targetOptions: { label: string; value: any }[] = []
      let label = ''
      if (item.targetType === 1) {
        const res = await CategoryLevelApi.getCategoryLevelPage({ pageNo: 1, pageSize: 1, id: item.targetId } as any)
        const found = res.list && res.list.find(i => i.id === item.targetId)
        label = found ? found.levelName || found.name : String(item.targetId)
        targetOptions = found ? [{ label, value: item.targetId }] : []
      } else if (item.targetType === 2) {
        const res = await getCategoryList({ id: item.targetId } as any)
        const found = res && res.find(i => i.id === item.targetId)
        label = found ? found.name : String(item.targetId)
        targetOptions = found ? [{ label, value: item.targetId }] : []
      } else if (item.targetType === 3) {
        const res = await getSpuPage({ pageNo: 1, pageSize: 1, id: item.targetId } as any)
        const found = res.list && res.list.find(i => i.id === item.targetId)
        label = found ? found.name : String(item.targetId)
        targetOptions = found ? [{ label, value: item.targetId }] : []
      }
      return {
        ...createEmptySetting(),
        ...item,
        targetOptions: targetOptions as { label: string; value: any }[],
        targetId: item.targetId,
      } as CommissionSettingItem
    }))
  } else {
    console.log('agreement对象:', agreement)
    formData.commissionSettings = [createEmptySetting()]
  }
}
defineExpose({ open })

async function submitForm() {
  await formRef.value.validate()
  // 校验 targetId 必填、targetType+targetId 不重复、比例/金额范围
  const typeIdSet = new Set()
  for (const i of formData.commissionSettings) {
    // targetId 必填
    if (!i.targetId) {
      ElMessage.error(getTargetError(i.targetType))
      return
    }
    // targetType+targetId 唯一
    const key = `${i.targetType}_${i.targetId}`
    if (typeIdSet.has(key)) {
      ElMessage.error('同一目标类型下目标ID不能重复')
      return
    }
    typeIdSet.add(key)
    // 比例校验
    if (i.commissionType === 1) {
      if (i.commissionRate == null || i.commissionRate < 0 || i.commissionRate > 100) {
        ElMessage.error('佣金比例必须在0~100之间')
        return
      }
    }
    // 固定金额校验
    if (i.commissionType === 2) {
      if (i.fixedAmount == null || i.fixedAmount < 0) {
        ElMessage.error('固定佣金金额不能小于0')
        return
      }
      if (i.targetType === 3) {
        // 查商品价格
        const res = await getSpuPage({ id: i.targetId } as any)
        const found = res.list && res.list.find(spu => spu.id === i.targetId)
        if (found && i.fixedAmount > found.price) {
          ElMessage.error('固定佣金金额不能超过商品价格')
          return
        }
      }
    }
  }
  formLoading.value = true
  try {
    let submitFormData: Record<string, any> = {};
    submitFormData.agreementId = formData.agreementId;
    let submitCommissionData : Partial<ChannelCommissionSettingVO>[] = [];
    for (const i of formData.commissionSettings) {
      let  data: Partial<ChannelCommissionSettingVO> = {
        agreementId: formData.agreementId!,
        targetType: i.targetType!,
        targetId: i.targetId!,
        commissionType: i.commissionType!,
        commissionRate: i.commissionType === 1 ? i.commissionRate : undefined,
        fixedAmount: i.commissionType === 2 ? i.fixedAmount : undefined,
        status: formData.status!,
        remark: formData.remark
      };
      submitCommissionData.push(data);
    }

    submitFormData.status = formData.status;
    submitFormData.remark = formData.remark;
    submitFormData.commissionSettings = submitCommissionData;

    

    await ChannelCommissionSettingApi.createBatchChannelCommissionSetting(submitFormData)

    ElMessage.success('保存成功')
    dialogVisible.value = false
    // 可选：emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>

<style scoped>
.commission-setting-form {
  font-size: 18px;
}

.commission-setting-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
</style> 